(function() {
  'use strict';


  angular.module('mlApp')
    .factory('SessionsService', ['$state', '$q', 'CommonService', SessionsService]);

  function SessionsService($state, $q, CommonService) {

    var service = {
      login: login,
      loadCaptcha: loadCaptcha,
      checkCaptcha: checkCaptcha,
      logout: logout
    };

    return service;

    ////////////////////

    function login(data) {
      return $q(function(resolve, reject) {
        CommonService.post('sessions', data).then(function(userInfo) {
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          resolve(userInfo);
        }, function(msg) {
          reject(msg);
        });
      });
    }

    function logout() {
      CommonService.post('sessions/logout').then(function(userInfo) {
        localStorage.removeItem('userInfo');
        $state.go('login');
      }, function(msg) {
        throw msg;
      });
    }

    function loadCaptcha() {
      return CommonService.post('captcha');
    }

    function checkCaptcha(data) {
      return CommonService.get('captcha', data);
    }

  }
})();